package project.server.handlers;

import java.util.Iterator;

import project.server.handlers.Sessions;
import project.server.handlers.OutboundMessages;
import project.server.handlers.Client;
import project.shared.messages.AnswerMessage;
import project.shared.messages.StartMessage;
import project.shared.messages.WinMessage;

public class Messenger extends Thread {
	
	/** Hoiab endas klientide sessioone. */
	private Sessions activeSessions;
	
	/** Sisaldab väljuvaid sõnumeid. */
	private OutboundMessages outQueue;
	
	/**
	 * Loob uue Messenger-i.
	 *
	 * @param activeSessions klientide sessioonide objekt
	 * @param outQueue väljuvate sõnumite objekt
	 */
	public Messenger(Sessions activeSessions, OutboundMessages outQueue) {
		this.activeSessions = activeSessions;
		this.outQueue = outQueue;
		start();
	}
	
	/**Gets the first outbound message and sends it to specified clients
	 * @see java.lang.Thread#run()
	 */
	public void run() {
		while (true) {
			Object msg = outQueue.getMessage();

			synchronized (activeSessions) {
				Iterator<Client> itr = activeSessions.iterator();

				while (itr.hasNext()) {
					Client cli = itr.next();

					if (!cli.isAlive()) {
						itr.remove();
					} else if (msg == null) {
						continue;
					} else {
						if (msg instanceof StartMessage) {
							if (cli.p.gameId == ((StartMessage) msg).gameId) {
								cli.sendMessage((StartMessage) msg);
							}
						} else if (msg instanceof AnswerMessage) {
							if (cli.p.gameId == ((AnswerMessage) msg).gameId) {
								cli.sendMessage((AnswerMessage) msg);
							}
						} else if (msg instanceof WinMessage) {
							if (cli.p.gameId == ((WinMessage) msg).gameId) {
								cli.sendMessage((WinMessage) msg);
							}
						}
					}
				}
			}
		}
	}
}
